<?php
// +----------------------------------------------------------------------
// | UCToo [ Universal Convergence Technology ]
// +----------------------------------------------------------------------
// | Copyright (c) 2014-2021 https://www.uctoo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Patrick <contact@uctoo.com>
// +----------------------------------------------------------------------

namespace uctoo\util\logic;


use app\model\saas\Balance;
use app\model\saas\MerchantAccount;
use app\model\saas\ShopAccount;
use app\model\wechat\Applet;
use think\facade\Db;
use app\util\library\Mpopen;
use uctoo\ThinkEasyWeChat\MiniProgram\CloudFunction\ServiceProvider;

class ShopOrderLogic
{
    public static function dealRenewCommission(&$order){
        Db::startTrans();
        try{
            $commissionPrice = 0;
            $leaderStock = MerchantAccount::getLeaderStock($order['commission_saler_id']);
            // 校验分佣者  到期时间   库存
            if($leaderStock) {
                // 结算分佣
                $saler = Db::name('saas_saler_account')->alias('a')
                    ->join('saas_saler l', 'a.saler_level=l.saler_level')
                    ->where('a.id', $order['commission_saler_id'])
                    ->field('l.store_commission_json')->find();
                if ($saler) {
                    $salerCommission = json_decode($saler['store_commission_json'], true);
                    $rate = $salerCommission['k0']['value'] ?? 0;
                    $rate /= 100;
                    $commissionPrice = $order['order_price'] * $rate;
                }

                // 更新代理商分佣
                if($commissionPrice){
                    Db::name('order_renew')->where('order_id',$order['order_id'])->update(['commission_price'=>$commissionPrice]);
                    $saler_account = Db::name('saas_saler_account')->where('id', $order['commission_saler_id'])->lock(true)->find();
                    Db::name('saas_saler_account')->where('id', $order['commission_saler_id'])
                        ->update([
                            'store_renew_commission' => $saler_account['store_renew_commission'] + $commissionPrice,
                            'total_commission' => $saler_account['total_commission'] + $commissionPrice
                        ]);
                    Balance::addLog($order['commission_saler_id'],$commissionPrice,$order['order_id'],Balance::TYPE_RENEW_SHOP);
                }
            }else{
                // 解除关系
                MerchantAccount::update(['commission_saler_id' => 0],['id'=>$order['merchant_id']]);
            }

            Db::commit();
        }catch (\Exception $e){
            Db:s:rollback();
            Log::write('********************************************续费店铺支付回调-分佣处理************************','error');
            Log::write('order'.$order['order_sn']);
            Log::write($e->getMessage(),'error');
        }
    }

    public static function dealAddCommission(&$order){
        if(!$order['commission_saler_id']){
            return;
        }
        Db::startTrans();
        try{
            $commissionPrice = 0;
            $leaderStock = MerchantAccount::getLeaderStock($order['commission_saler_id']);
            // 校验分佣者  到期时间   库存
            if($leaderStock) {
                // 结算分佣
                $saler = Db::name('saas_saler_account')->alias('a')
                    ->join('saas_saler l', 'a.saler_level=l.saler_level')
                    ->where('a.id', $order['commission_saler_id'])
                    ->field('l.store_commission_json')->find();
                if ($saler) {
                    $salerCommission = json_decode($saler['store_commission_json'], true);
                    $rate = $salerCommission['k1']['value'] ?? 0;
                    $rate /= 100;
                    $commissionPrice = $order['order_price'] * $rate;
                }

                // 更新代理商分佣
                if($commissionPrice){
                    Db::name('order_renew')->where('order_id',$order['order_id'])->update(['commission_price'=>$commissionPrice]);
                    $saler_account = Db::name('saas_saler_account')->where('id', $order['commission_saler_id'])->lock(true)->find();
                    Db::name('saas_saler_account')->where('id', $order['commission_saler_id'])
                        ->update([
                            'store_branch_commission' => $saler_account['store_branch_commission'] + $commissionPrice,
                            'total_commission' => $saler_account['total_commission'] + $commissionPrice
                        ]);
                    Balance::addLog($order['commission_saler_id'],$commissionPrice,$order['order_id'],Balance::TYPE_ADD_SHOP);
                }
            }else{
                // 解除关系
                MerchantAccount::update(['commission_saler_id' => 0],['id'=>$order['merchant_id']]);
            }

            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            Log::write('********************************************添加店铺支付回调-分佣处理************************','error');
            Log::write('order'.$order['order_sn']);
            Log::write($e->getMessage(),'error');
        }
    }


    public function updateShopExpireTime(&$order){
        // 更新店铺有效期
        ShopAccount::update(['expire_time' => $order['renew_expire_time']],['id'=>$order['shop_id']]);
        $applet = Applet::appInfo($order['appid']);
        if(!$applet){
            return;
        }
        $app = invoke(Mpopen::class);
        $mapp = $app->miniProgram($applet['appid'],$applet['refresh_token']);
        $mapp->config->add('env',$applet['env']);
        $postBody = [
            '$url' => 'shop/edit',
            'data' => [
                'id' => $order['shop_id'],
                'expireTime' => $order['renew_expire_time']
            ]
        ];
        $mapp->registerProviders([ServiceProvider::class]);
        $mapp->cloud_function->invokeFunction('meiye',$postBody);
    }
}